#测试对数据库的操作
# 新建 读取 更新 删除 
#http://wenku.baidu.com/view/9d63a1134431b90d6c85c77e.html

import MySQLdb
import sys
try:
   connection = MySQLdb.connect(user="root",passwd="mhfc2010",host="127.0.0.1",db="nono")
   #获取操作游标
   cursor = connection.cursor()  
##   #执行SQL,创建一个数据库.  
##   cursor.execute("""create database python """)  

   value = [1,"inert nono"]
   cursor.execute('use python')
##   cursor.execute("""create table pyTest( id int, info varchar(100)) if not exists pyTest""")
   cursor.execute('''insert into pyTest values(1,"sb")''');

   values =[]
   #生成插入参数值  
   for i in range(20):  
      values.append((i,'"Hello mysqldb, I am recoder ' + str(i) + '"'))
      print ("""insert into pyTest values(%s,%s) """%values[i])
##      cursor.execute("""insert into pyTest values(%s,%s) """%values[i]);   
#插入多条记录
 
   cursor.executemany("""insert into pyTest values(%s,%s) """%values);

   
   count = cursor.execute('select * from pyTest')

   print ("只获取一条记录:" ) 
   result = cursor.fetchone();  
   print (result)  

   print ("只获取5条记录:"  )
   results = cursor.fetchmany(5)  
   for r in results:  
      print (r)  

   print ("获取所有结果:"  )
##   #重置游标位置，0,为偏移量，mode＝absolute | relative,默认为relative,  
   cursor.scroll(0,mode='absolute')  
   #获取所有结果  
   results = cursor.fetchall()  
   for r in results:  
      print (r) 
   #关闭连接，释放资源
   cursor.close();  
except:
   print (sys.exc_info()[0],sys.exc_info()[1] )
   print ("Could not connect to MySQL server.")
   exit( 0 )
